import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:musicapp/model/user.dart';
import 'package:musicapp/utils/navigator_util.dart';
import 'package:musicapp/utils/net_utils.dart';
import 'package:musicapp/utils/utils.dart';

import '../application.dart';

class UserModel with ChangeNotifier {
  User _user;
  User get user => _user;

  /// 初始化user
  void initUser() {
    if(Application.sp.containsKey('user')) {
      String s = Application.sp.getString('user');
      _user = User.fromJson(json.decode(s));
    }
  }

  /// 登陆
  void login(BuildContext context, String phone, String pwd) async {
    User user = await NetUtils.login(context, phone, pwd);
    if(user.code > 299) {
      Utils.showToast(user.msg ?? '登录失败，请检查账号密码');
      return;
    }
    Utils.showToast(user.msg ?? '登录成功');
    _saveUserInfo(user);
    NavigatorUtil.goHomePage(context);
  }

  void _saveUserInfo(User user) {
    _user = user;
    Application.sp.setString('user', json.encode(user.toJson()));
  }
}